import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'


Vue.use(VueRouter)
// export default new Router({
//   mode: 'history',
//   routers: [
//     { path: '/', redirect: '/login' },
//     { path: '/login', component: Login }
//   ]
// })

const routes = [
  {
    path: '/',
    redirect: '/login'//重定向   往往是服务器向外部发的请求跳转;输入“/”直接跳转到“/login”
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',//重定向， 访问homo时自动跳转到welcome
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path:'/users',
        component:Users//component属性可以用来指定要展示的组件名称
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 为路由对象，添加 beforeEach 导航守卫
router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页，next() 直接放行  
  if (to.path === '/login') return next()
  // 从 sessionStorage 中获取到 保存的 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token，强制跳转到登录页  next('/login')强制跳转
  if (!tokenStr) return next('/login')
  next()
})

export default router

